
package cn.cmcc.online.smsapi.sdk.db.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.ContentValues;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.DBManager;
import cn.cmcc.online.smsapi.sdk.db.XyCursor;
import cn.cmcc.online.smsapi.sdk.db.base.BaseManager;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.util.StringUtils;
/* SDK-509 huangzhiqiang 20160627 start */
import java.util.Set;
/* SDK-509 huangzhiqiang 20160627 end */
/* SDK-632 hewengao 20161010 start*/
import android.database.sqlite.SQLiteDatabase;
/* SDK-632 hewengao 20161010 end*/
public class SceneconfigManager {


	public static final int NOTFINISH = 0;
	public static final int FINISH = 1;

	public static final int SCENE_TYPE_POPUP =0;//0:弹窗
	public static final int SCENE_TYPE_BUBBLE =1;//1:汽泡

    public static final String SCENE_ID = "scene_id";

    public static final String SCENEVERSION = "sceneVersion";

	public static final String SCENETYPE = "sceneType";//0:弹窗 1:汽泡

    public static final String TABLE_NAME = "tb_scene_config";

    public static final String IS_CHECK = "isCheck";

    public static final String IS_USE = "isUse";//标志情景是否已用0是没用过，1是用过

    public static final String USECOUNT = "useCount";//标志情景用的次数
	/* SDK-632 hewengao 20161009 start*/
	public static final String lAST_UPDATE_TIME ="last_update_time";//最后更新时间
    /* SDK-632 hewengao 20161009 end*/
//    public static final String SCENEURL = "scene_url";//xml下载路径    

    public static final String DROP_TABLE = " DROP TABLE IF EXISTS " + TABLE_NAME;
	/* SDK-632 hewengao 20161009 start*/
    public static final String CREATE_TABLE = "create table  if not exists " + TABLE_NAME + " ("

    + SCENE_ID + " TEXT,"+ SCENETYPE +" INTEGER DEFAULT '0',"
			+ IS_CHECK +" INTEGER DEFAULT '0',"
			+ SCENEVERSION + " TEXT,"
			+ IS_USE+" INTEGER DEFAULT '0',"
			+ lAST_UPDATE_TIME+" INTEGER DEFAULT '0',"
			+USECOUNT+" INTEGER DEFAULT '0'"
			+")";
	/* SDK-632 hewengao 20161009 end*/
	public static final String ADD_SCENETYPE = "ALTER TABLE "+ TABLE_NAME +" ADD COLUMN "+SCENETYPE+" INTEGER DEFAULT '-1'";

	public static final String ADD_IS_CHECK = "ALTER TABLE "+ TABLE_NAME +" ADD COLUMN "+IS_CHECK+" INTEGER DEFAULT '0'";

	public static final String ADD_USECOUNT = "ALTER TABLE "+ TABLE_NAME +" ADD COLUMN "+USECOUNT+" INTEGER DEFAULT '0'";

	public static final String ADD_IS_USE = "ALTER TABLE "+ TABLE_NAME +" ADD COLUMN "+IS_USE+" INTEGER DEFAULT '0'";

	/* SDK-632 hewengao 20161009 start*/
	public static final String ADD_lAST_UPDATE_TIME = "ALTER TABLE "+ TABLE_NAME +" ADD COLUMN "+lAST_UPDATE_TIME+" INTEGER DEFAULT '0'";
	/* SDK-632 hewengao 20161009 end*/

	 public static List<Sceneconfig> queryAllSceneconfig(int sceneType,int type){
			List<Sceneconfig> sceneconfigList = new ArrayList<Sceneconfig>();
			XyCursor cur = null;
			try {
				String sqlWhere="";
				if(sceneType == SceneconfigManager.SCENE_TYPE_BUBBLE){
					sqlWhere = SCENETYPE+" = "+sceneType +" and "+IS_CHECK+" = "+type;
				}else{
					sqlWhere = SCENETYPE+" != "+SceneconfigManager.SCENE_TYPE_BUBBLE+" and "+IS_CHECK+" = "+type;
				}
				cur =DBManager.query(TABLE_NAME,
						new String[]{SCENE_ID,SCENEVERSION},
						sqlWhere ,null);
				if(cur != null&&cur.getCount()>0){
					int sceneIdIndex =cur.getColumnIndex(SCENE_ID);
					int sceneVersionIndex =cur.getColumnIndex(SCENEVERSION);


					Sceneconfig tempConfig=null;
					while(cur.moveToNext()){
						tempConfig = new Sceneconfig();
						tempConfig.sceneId=cur.getString(sceneIdIndex);
						tempConfig.sceneVersion=cur.getString(sceneVersionIndex);


						sceneconfigList.add(tempConfig);
					}

				}
			} catch (Throwable e) {
//				e.printStackTrace();
			    /*SDK-550 hewengao 20160719 start*/
	            LogManager.w(Constant.TAG, "queryAllSceneconfig error: ", e);
	            /*SDK-550 hewengao 20160719 end*/
			}finally{
			    XyCursor.closeCursor(cur, true);
			}
			return sceneconfigList;
		}
	/* SDK-632 hewengao 20161009 start*/
    public static List<Sceneconfig> queryAllSceneconfig(int sceneType,long periodTime){
    /* SDK-632 hewengao 20161009 start*/
		List<Sceneconfig> sceneconfigList = new ArrayList<Sceneconfig>();
		XyCursor cur = null;
		try {
			String sqlWhere="";
			if(sceneType == SceneconfigManager.SCENE_TYPE_BUBBLE){
				sqlWhere = SCENETYPE+" = "+sceneType +" and "+IS_USE +" = 1";
			}else{
				sqlWhere = SCENETYPE+" != "+SceneconfigManager.SCENE_TYPE_BUBBLE+" and "+IS_USE +" = 1";
			}
            /* SDK-632 hewengao 20161009 start*/
            long time = System.currentTimeMillis() - periodTime;
            sqlWhere = sqlWhere + " and " + lAST_UPDATE_TIME + " < " + time;
            /* SDK-632 hewengao 20161009 end*/
			cur =DBManager.query(TABLE_NAME,
					new String[]{SCENE_ID,SCENEVERSION,USECOUNT},
					sqlWhere ,null);
			if(cur != null&&cur.getCount()>0){
				int sceneIdIndex =cur.getColumnIndex(SCENE_ID);
				int sceneVersionIndex =cur.getColumnIndex(SCENEVERSION);
				int useCount=cur.getColumnIndex(USECOUNT);

				Sceneconfig tempConfig=null;
				while(cur.moveToNext()){
					tempConfig = new Sceneconfig();
					tempConfig.sceneId=cur.getString(sceneIdIndex);
					tempConfig.sceneVersion=cur.getString(sceneVersionIndex);
					tempConfig.count=cur.getInt(useCount);
					sceneconfigList.add(tempConfig);
				}

			}
		} catch (Throwable e) {
//			e.printStackTrace();
		    /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "queryAllSceneconfig: ", e);
            /*SDK-550 hewengao 20160719 end*/
		}finally{
		    XyCursor.closeCursor(cur, true);
		}
		return sceneconfigList;
	}

    /**
	 * 获取情景版本数据
	 * @param scene_id 情景
	 * @param sceneType 0:弹窗 1:汽泡
	 * @return
	 */
	public static Sceneconfig querySceneconfigBySceneId(String scene_id,int sceneType){
		XyCursor cur = null;
		try {
			String sqlWhere="";
			if(sceneType == SceneconfigManager.SCENE_TYPE_BUBBLE){
				sqlWhere =SCENE_ID+"=? and "+SCENETYPE+" = "+sceneType;
			}else{
				sqlWhere =SCENE_ID+"=? and "+SCENETYPE+" != "+SceneconfigManager.SCENE_TYPE_BUBBLE;
			}
			cur =DBManager.query(TABLE_NAME,
					new String[]{SCENE_ID,SCENEVERSION},
					sqlWhere ,new String[]{scene_id+""},null,null,null,"1");
			if(cur != null&&cur.getCount()>0){
				int versonIndex =cur.getColumnIndex(SCENEVERSION);
				int sceneIdIndex =cur.getColumnIndex(SCENE_ID);



				Sceneconfig tempConfig=null;
				while(cur.moveToNext()){
					tempConfig = new Sceneconfig();
					tempConfig.sceneVersion=cur.getString(versonIndex);
					tempConfig.sceneId=cur.getString(sceneIdIndex);


				}
				return tempConfig;
			}
		} catch (Throwable e) {
//			e.printStackTrace();
		    /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "querySceneconfigBySceneId error: ", e);
            /*SDK-550 hewengao 20160719 end*/
		}finally{
		    XyCursor.closeCursor(cur, true);
		}
		return null;
	}

	public static void insertOrUpdate(String sceneid,String sceneVersion,int sceneType){
		 XyCursor xyCursor = null;
	        try {

	            if (!StringUtils.isNull(sceneid)) {
	                xyCursor = DBManager.query(TABLE_NAME, new String[] {
	                		SCENE_ID
	                }, SCENE_ID + " = ? and "+SCENETYPE+" = ?", new String[] {
	                		sceneid,sceneType+""
	                });
	            }
	        	ContentValues values=setContentValues( sceneid, sceneVersion, sceneType);
	            if (xyCursor != null && xyCursor.getCount() > 0) {
	            	  DBManager.update(TABLE_NAME, values,
	            			  SCENE_ID + " = ? and "+SCENETYPE+" = ?", new String[] {
		                		sceneid,sceneType+""
		                });
	            } else {

	                DBManager.insert(TABLE_NAME,  values);
	            }

	        } catch (Throwable e) {
//	            e.printStackTrace();
	            /*SDK-550 hewengao 20160719 start*/
	            LogManager.w(Constant.TAG, "insertOrupdate error: ", e);
	            /*SDK-550 hewengao 20160719 end*/
	        } finally {
	            XyCursor.closeCursor(xyCursor, true);

	        }
	}

	public static long insertOrUpdate(Sceneconfig sceneconfig,int sceneType){
        long result = -1;
        XyCursor xyCursor = null;
        try {

            if (!StringUtils.isNull(sceneconfig.sceneId)) {

                xyCursor = DBManager.query(TABLE_NAME, new String[] {
                		SCENE_ID,
                }, SCENE_ID + " = ?  and "+SCENETYPE+" = ?", new String[] {
                		sceneconfig.sceneId,sceneType+""
                });
            }
            ContentValues values=setContentValues(sceneconfig,sceneType);
            if (xyCursor != null && xyCursor.getCount() > 0) {
            	 DBManager.update(TABLE_NAME, values,
           			  SCENE_ID + " = ? and "+SCENETYPE+" = ?", new String[] {
            			 sceneconfig.sceneId,sceneType+""
	                });
            } else {

                result = DBManager.insert(TABLE_NAME,  values);
            }

        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "insertOrUpdate error: ", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            XyCursor.closeCursor(xyCursor, true);

        }
        return result;
    }

	public static  ContentValues setContentValues(Sceneconfig sceneconfig,int sceneType){
		ContentValues values=new ContentValues();
		if(!StringUtils.isNull(sceneconfig.sceneVersion))
		{
			values.put(SCENEVERSION, sceneconfig.sceneVersion);
		}
		values.put(SCENE_ID, sceneconfig.sceneId);
		values.put(SCENETYPE,sceneType);
		values.put(IS_CHECK,sceneconfig.isDownload);

		return values;
	}

	public static  ContentValues setContentValues(Sceneconfig sceneconfig){
		ContentValues values=new ContentValues();
//		if(!StringUtils.isNull(sceneconfig.sceneVersion))
//		{
//			values.put(SCENEVERSION, sceneconfig.sceneVersion);
//		}	
//		values.put(SCENE_ID, sceneconfig.sceneId);
//		values.put(SCENETYPE,sceneconfig.sceneType);
//		values.put(IS_CHECK,sceneconfig.isDownload);
		values.put(USECOUNT,sceneconfig.count);
		values.put(IS_USE,sceneconfig.isUse);
		return values;
	}


	public static  ContentValues setContentValues(String sceneid,String sceneVersion,int sceneType){
		ContentValues values=new ContentValues();
		values.put(SCENE_ID, sceneid);
		values.put(SCENETYPE,sceneType);
		if(!StringUtils.isNull(sceneVersion))
		{
			values.put(SCENEVERSION,sceneVersion);
		}

		return values;
	}

	public static void deleteSceneconfigById(String scenid,int sceneType){
		try {
			String sqlWhere="";
			if(sceneType == SceneconfigManager.SCENE_TYPE_BUBBLE){
				sqlWhere =SCENE_ID+"=? and "+SCENETYPE+" = "+sceneType;
			}else{
				sqlWhere =SCENE_ID+"=? and "+SCENETYPE+" != "+SceneconfigManager.SCENE_TYPE_BUBBLE;
			}

			DBManager.delete(TABLE_NAME, sqlWhere, new String[] {scenid});
		} catch (Throwable e) {
//			e.printStackTrace();
		    /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "deleteSceneconfigById error: ", e);
            /*SDK-550 hewengao 20160719 end*/
		}
	}


    public static void deleteAll(){
    	try {
    		DBManager.delete(TABLE_NAME, null,null);
		} catch (Throwable e) {
//			e.printStackTrace();
		    /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "deleteAll: ", e);
            /*SDK-550 hewengao 20160719 end*/
		}
    }
    /**
     * 统计情景使用次数
     * @param paramsMap
     */
    public static void insertOrUpdate(HashMap<String, String> paramsMap) {
        if (paramsMap == null)
            return;
        String sceneId = paramsMap.get("titleNo");
        Sceneconfig sceneconfig = new Sceneconfig();
        sceneconfig.sceneId = sceneId;
        sceneconfig.count = 1;//初始化次数为1
        ContentValues values = null;
        XyCursor xyCursor = null;
        try {

            if (!StringUtils.isNull(sceneconfig.sceneId)) {
                xyCursor = DBManager.query(TABLE_NAME, new String[] {
                		SCENE_ID, IS_USE,USECOUNT
                }, SCENE_ID + " = ? ", new String[] {
                		sceneconfig.sceneId
                });
            }
            if (xyCursor != null && xyCursor.getCount() > 0) {
				while(xyCursor.moveToNext()){
					int countIndex = xyCursor.getColumnIndex(USECOUNT);
//                int sceneVersionindex = xyCursor.getColumnIndex(SCENEVERSION);
					int c = xyCursor.getInt(countIndex) + 1;
//                sceneconfig.sceneVersion=xyCursor.getString(sceneVersionindex);
					sceneconfig.isUse= 1 ;
					sceneconfig.count = c;
//                sceneconfig.isDownload=xyCursor.getInt(xyCursor.getColumnIndex(IS_CHECK));
					values = setContentValues(sceneconfig);
					//更新解析次数
					DBManager.update(TABLE_NAME, values, SCENE_ID+" = ? ", new String[]{
							sceneconfig.sceneId+""});
				}
			}
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "insertOrUpdate: ", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            XyCursor.closeCursor(xyCursor, true);
        }
        /* SDK-632 hewengao 20161009 start*/
        //更新使用的情景
        SceneRuleManager.updateSceneIdUsed(sceneId);
        /* SDK-632 hewengao 20161009 start*/
    }

    /* SDK-509 huangzhiqiang 20160627 start */
    /**
     * 通过情景ID及情景类型更新检查状态
     *
     * @param sceneIds
     * @param sceneType 情景类型(0:弹窗 1:汽泡)
     * @param isCheck 0:未完成 1:已完成
     * @return
     */
    public static void updateIsCheckBySceneIdAndSceneType(Set<String> sceneIds, int sceneType, int isCheck) {
        if (sceneIds == null || sceneIds.isEmpty()) {
            return;
        }
        try {
            int size = sceneIds.size();
            String placeholders = SmsParseRecorder.makePlaceholders(size);
            String whereClause = SCENE_ID + " IN(" + placeholders + ") AND " + SCENETYPE + "=?";
            String[] whereArgs = sceneIds.toArray(new String[size + 1]);
            whereArgs[size] = String.valueOf(sceneType);
            DBManager.update(TABLE_NAME, BaseManager.getContentValues(null, IS_CHECK, String.valueOf(isCheck)),
                    whereClause, whereArgs);
        } catch (Throwable e) {
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "updateIsCheckBySceneIdAndSceneType error:",e);
            /*SDK-550 hewengao 20160719 end*/
        }
    }

    /**
     * 标记指定情景为已使用并重置使用次数为0
     *
     * @param sceneIds
     * @return
     */
    public static void setIsUseAndResetUseCount(Set<String> sceneIds) {
        if (sceneIds == null || sceneIds.isEmpty()) {
            return;
        }
        try {
            int size = sceneIds.size();
            String placeholders = SmsParseRecorder.makePlaceholders(size);
            String whereClause = SCENE_ID + " IN(" + placeholders + ")";
            String[] whereArgs = sceneIds.toArray(new String[size]);
            DBManager.update(TABLE_NAME, BaseManager.getContentValues(null, IS_USE, "1", USECOUNT, "0"),
                    whereClause, whereArgs);
        } catch (Throwable e) {
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "setIsUseAndResetUseCount error:", e);
            /*SDK-550 hewengao 20160719 end*/
        }
    }

    public static void insertOrUpdateSceneConfig(List<Sceneconfig> sceneConfigs, int sceneType) {
        if (sceneConfigs == null || sceneConfigs.isEmpty()) {
            return;
        }
        for (Sceneconfig sceneConfig : sceneConfigs) {
            if (sceneConfig != null) {
                insertOrUpdate(sceneConfig.sceneId, sceneConfig.sceneVersion, sceneType);
            }
        }
    }
    /* SDK-509 huangzhiqiang 20160627 end */

    /* SDK-632 hewengao 20161010 start*/
    public static int updateSceneConfigUpdateTime(List<Sceneconfig> listSceneConfig){
        SQLiteDatabase db = null;
        try {
            if(listSceneConfig == null || listSceneConfig.isEmpty()){
                return 0;
            }
            db = DBManager.getSQLiteDatabase();
            db.beginTransaction();
            String sql = "update  " +TABLE_NAME+
                    " set " +lAST_UPDATE_TIME+" = "+System.currentTimeMillis()+
                    " WHERE "+SCENE_ID+" = ?";
            for(Sceneconfig config: listSceneConfig){
                db.execSQL(sql,new String[]{config.sceneId});
            }
        } catch (Throwable e) {
            LogManager.w(Constant.TAG, "1updateSceneRuleUpdateTime: ", e);
        } finally {
            try {
                if (db != null) {
                    db.setTransactionSuccessful();
                    db.endTransaction();
                }
            }catch (Throwable e){
                LogManager.w(Constant.TAG, "2updateSceneRuleUpdateTime: ", e);
            }
            DBManager.close(db);
        }
        return 0;
    }
    /* SDK-632 hewengao 20161010 start*/
}
